package com.spring.sunflower.common

import android.content.Intent
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.lxj.xpopup.XPopup
import com.spring.sunflower.R
import com.spring.sunflower.base.BaseFragment
import com.spring.sunflower.base.BaseObserver
import com.spring.sunflower.bean.*
import com.spring.sunflower.constant.Constant
import com.spring.sunflower.http.AppRetrofit
import com.spring.sunflower.util.AppUtils
import com.spring.sunflower.util.PayUtils
import com.spring.sunflower.widget.BottomPayDialog
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import java.util.HashMap

/**
 * Created by Kevin on 2021/7/17<br/>
 *
 * Describe:<br/>
 */
class BalanceFragment : BaseFragment<BalancePresenter>(), CommonContract.BalanceView {
    private var tvCoin: TextView? = null
    private var tvDone: TextView? = null
    private var rvRecyclerView: RecyclerView? = null
    private var mAdapter: BalanceAdapter? = null
    private var mData: MutableList<BalanceBean.Data> = ArrayList()
    private var clickPos = 0
    private var tvTip: TextView? = null

    //    private var llChargeRecord: LinearLayout? = null
    private var mUserID = ""
    private var shouldCheckIfPaySuccess = false//是否调用判断支持成功接口
    private var mOrderId = ""
    private var currentEnvironment: String = ""
    override fun setLayoutResId(): Int = R.layout.fragment_balance

    override fun initView() {
//        llChargeRecord = mView.findViewById(R.id.llChargeRecord)
        currentEnvironment = getField(Constant.KEY_ENVIRONMENT, Constant.ENVIRONMENT_PRODUCT)
        mUserID = getField(Constant.KEY_USERID, "")
        tvTip = mView.findViewById(R.id.tvTip)
        tvCoin = mView.findViewById(R.id.tvCoin)
//        tvCoin?.text = getField(Constant.KEY_MONEY, "0")
        rvRecyclerView = mView.findViewById(R.id.rvRecyclerView)
        tvDone = mView.findViewById(R.id.tvDone)
        mAdapter = BalanceAdapter(R.layout.adapter_item_balance, mData)
        val gridLayoutManager = GridLayoutManager(mActivity, 3)
        rvRecyclerView?.layoutManager = gridLayoutManager
        rvRecyclerView?.adapter = mAdapter
        mPresenter.getBalance()
        mAdapter?.setOnItemClickListener(object : OnItemClickListener {
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
                clickPos = position
                for (index in mData.indices) {
                    mData[index].checked = index == position
                }
                mAdapter?.notifyDataSetChanged()

            }

        })
    }

    override fun initData() {
    }

    override fun initListener() {
        tvTip?.setOnClickListener {
            startNewActivity(ChargeRecordActivity::class.java)
        }
        val bottomPayDialog = BottomPayDialog(mActivity)
        bottomPayDialog.setOnPaySelectListener(object : BottomPayDialog.OnPaySelectListener {
            override fun onPaySelect(position: Int) {
//                showToast(if (position == 0) "支付宝" else "微信")
                val data = mData[clickPos]
                if (position == 0) {
                    mPresenter.aliPayGenerate(data.id)
                } else {
//                    val intent = Intent(mActivity, WebViewH5PayActivity::class.java)
//                    intent.putExtra("exchangeID", data.id)
//                    intent.putExtra("type", "1")
//                    intent.putExtra("userIdOrMobile", mUserID)
//                    startActivity(intent)
//                    mPresenter.weChatPayH5(data.id, mUserID)
                    if (AppUtils.isAppInstalled(mActivity, "com.tencent.mm")) {
//                        mPresenter.weChatPayGenerate(data.id)
                        val map: MutableMap<String, String> = HashMap()
                        map["exchangeId"] = data.id
                        map["type"] = "1"
                        map["token"] = getField(Constant.KEY_TOKEN, "")
                        map["MID"] = mUserID
                        map["userIdOrMobile"] = mUserID
                        if (currentEnvironment == Constant.ENVIRONMENT_PRODUCT) {
                            mPresenter.getWeChatH5PayProduct(map)
                        } else {
                            mPresenter.getWeChatH5Pay(map)
                        }
                    } else {
//                        mPresenter.weChatPayH5()
                        showToast("微信未安装")
                    }
//                    val appRetrofit = AppRetrofit("http://www.wanyuyue.top/")
//                    val map: MutableMap<String, String> = HashMap()
//                    map["exchangeId"] = data.id
//                    map["type"] = "1"
//                    map["token"]=getField(Constant.KEY_TOKEN,"")
//                    map["MID"]=mUserID
//                    map["userIdOrMobile"] = mUserID
//                    val weChatHe = appRetrofit.httpService.getWeChatHe(map)
//                    weChatHe.subscribeOn(Schedulers.io())
//                        .subscribeOn(AndroidSchedulers.mainThread())
//                        .observeOn(AndroidSchedulers.mainThread())
//                        .subscribeWith(object : BaseObserver<WeChatH5Bean>() {
//                            override fun onSuccess(bean: WeChatH5Bean?) {
//                                val datas = bean!!.datas
//                                val mwebUrl = datas.mwebUrl
//                                val intent = Intent(mActivity, WebViewH5PayActivity::class.java)
//                                intent.putExtra("mWebUrl", mwebUrl)
//                                startActivity(intent)
//                            }
//
//                            override fun onError(status: Int, msg: String?) {
//                            }
//
//                        })


                }
                bottomPayDialog.dismiss()
            }

        })
        tvDone?.setOnClickListener {
            XPopup.Builder(mActivity)
                .enableDrag(false)
                .asCustom(
                    bottomPayDialog
                )
                .show()
        }
//        llChargeRecord?.setOnClickListener {
//            startNewActivity(ChargeRecordActivity::class.java)
//        }
    }

    override fun onResume() {
        super.onResume()
        mPresenter.getAccount()
        if (shouldCheckIfPaySuccess && !TextUtils.isEmpty(mOrderId)) {
            mPresenter.getWeChatH5PayResult(mOrderId)
            shouldCheckIfPaySuccess = false
        }
    }

    override fun loadData() {
    }

    override fun setPresenter(): BalancePresenter {
        return BalancePresenter(this)
    }

    override fun showAccount(data: AccountBean.DatasBean?) {
        tvCoin?.setText(data!!.money)
        saveField(Constant.KEY_MONEY, data!!.money)
        val dialyAward = data.taskDailyAward.toInt()
        val newerAward = data.taskNewbieAward.toInt()
        val signAward = data.signInAward.toInt()
        val i = dialyAward + newerAward + signAward
        printD("i=${i}")
        saveField(Constant.KEY_AWARD, i.toString())
        saveField(Constant.KEY_INCOME, data!!.integral)
    }

    override fun showBalanceList(data: MutableList<BalanceBean.Data>?) {
        for (index in data!!.indices) {
            if (index == 0) {
                data[index].checked = true
            }
        }
        mAdapter?.addData(data!!)
    }

    override fun showAliGenerateData(data: String?) {
        PayUtils.getInstance(mActivity).payWithAlipay(data)
    }

    override fun showAliGenerateH5Data(data: String?) {
    }

    override fun showAliGenerateVipData(data: String?) {
    }

    override fun showWeChatGenerateData(data: WeChatPayBean.DatasBean?) {
        PayUtils.getInstance(mActivity).payWithWeChatPay(data!!)
    }

    override fun showWeChatGenerateH5Data(data: WeChatPayBean.DatasBean?) {
        val packageX = data!!.packageX
        val prepayid = data!!.prepayid


    }

    override fun showWeChatGenerateVipData(data: WeChatPayBean.DatasBean?) {
    }

    override fun showWeChatH5Data(data: WeChatH5Bean.DatasBean?) {
        val mwebUrl = data!!.mwebUrl
        mOrderId = data!!.orderNo
        val intent = Intent(mActivity, WebViewH5PayActivity::class.java)
        intent.putExtra("mWebUrl", mwebUrl)
        startActivity(intent)
        shouldCheckIfPaySuccess = true
    }

    override fun showWeChatH5PayResult(data: WeChatH5PayResultBean.DatasBean?) {
        val status = data!!.status
        when (status) {
            "0" -> {
                showToast("未完成支付")
            }
            "1" -> {
                showToast("支付成功")
            }
            "2" -> {
                showToast("取消支付")
            }
            "3" -> {
                showToast("订单已验证")
            }
            "4" -> {
                showToast("订单号不存在")
            }
            "5" -> {
                showToast("人工确认-已充值")
            }
        }

    }


}